import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 计算属性
  const isLoggedIn = computed(() => {
    return !!token.value && !!userInfo.value.id
  })
  
  const isStudent = computed(() => {
    return userInfo.value.role === 'STUDENT'
  })
  
  const isOrganizer = computed(() => {
    return userInfo.value.role === 'ORGANIZER'
  })
  
  const isAdmin = computed(() => {
    return userInfo.value.role === 'ADMIN'
  })
  
  // 方法
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  
  const login = async (credentials) => {
    try {
      const response = await api.post('/users/login', credentials)
      const { data: user } = response.data
      
      // 后端返回的是用户信息，前端需要生成token或使用session
      setUserInfo(user)
      setToken('user-logged-in') // 临时token，实际应该由后端提供
      
      return response.data
    } catch (error) {
      throw error
    }
  }
  
  const register = async (userData) => {
    try {
      const response = await api.post('/users/register', userData)
      return response.data
    } catch (error) {
      throw error
    }
  }
  
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  const updateProfile = async (profileData) => {
    try {
      const response = await api.put(`/users/${userInfo.value.userId}`, profileData)
      setUserInfo(response.data.data)
      return response.data
    } catch (error) {
      throw error
    }
  }
  
  const checkLoginStatus = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken && storedUserInfo) {
      token.value = storedToken
      userInfo.value = JSON.parse(storedUserInfo)
    }
  }
  
  return {
    // 状态
    token,
    userInfo,
    
    // 计算属性
    isLoggedIn,
    isStudent,
    isOrganizer,
    isAdmin,
    
    // 方法
    setToken,
    setUserInfo,
    login,
    register,
    logout,
    updateProfile,
    checkLoginStatus
  }
})